"""
主程序入口
提供统一的命令行界面
"""
import argparse
import logging
from pathlib import Path

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def main():
    parser = argparse.ArgumentParser(
        description="医学文献智能检索与摘要平台",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
使用示例:
  python main.py crawl --query "COVID-19" --max-results 100    # 爬取论文
  python main.py build-index                                     # 构建索引
  python main.py server                                          # 启动API服务器
  python main.py streamlit                                       # 启动Streamlit界面
        """
    )
    
    subparsers = parser.add_subparsers(dest="command", help="可用命令")
    
    # 爬取命令
    crawl_parser = subparsers.add_parser("crawl", help="爬取PubMed论文")
    crawl_parser.add_argument("--query", type=str, default="", help="搜索查询词")
    crawl_parser.add_argument("--max-results", type=int, default=100, help="最大结果数")
    
    # 构建索引命令
    build_parser = subparsers.add_parser("build-index", help="构建向量检索索引")
    
    # 启动服务器命令
    server_parser = subparsers.add_parser("server", help="启动FastAPI服务器")
    server_parser.add_argument("--host", type=str, default="0.0.0.0", help="主机地址")
    server_parser.add_argument("--port", type=int, default=8000, help="端口号")
    
    # Streamlit命令
    streamlit_parser = subparsers.add_parser("streamlit", help="启动Streamlit界面")
    
    args = parser.parse_args()
    
    if args.command == "crawl":
        from crawl_papers import crawl_and_save
        crawl_and_save(query=args.query, max_results=args.max_results)
    
    elif args.command == "build-index":
        from build_index import build_index
        build_index()
    
    elif args.command == "server":
        import uvicorn
        from api.main import app
        uvicorn.run(app, host=args.host, port=args.port, reload=True)
    
    elif args.command == "streamlit":
        import subprocess
        import sys
        subprocess.run([sys.executable, "-m", "streamlit", "run", "streamlit_app.py"])
    
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
